import { useEffect, useRef } from 'react'

export const useInterval = (
	callback: Function,
	delay?: number | null,
	options?: {
		immediate?: boolean
	}
) => {
	const immediate = options?.immediate
	const savedCallback = useRef<Function>(() => {})

	savedCallback.current = callback

	useEffect(() => {
		if (delay !== null) {
			if (immediate) {
				savedCallback.current?.()
			}
			const interval = setInterval(() => savedCallback.current?.(), delay || 0)
			return () => clearInterval(interval)
		}

		return undefined
	}, [delay])
}
